package ws.quokka.plugin.depset;

/**
 *
 */

import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.types.FileSet;
import ws.quokka.core.metadata.Metadata;
import ws.quokka.core.metadata.MetadataAware;
import ws.quokka.core.plugin_spi.support.Setter;
import ws.quokka.core.repo_spi.RepoArtifactId;
import ws.quokka.plugin.lifecycle.LifeCycleImpl;

import java.io.File;
import java.util.Iterator;
import java.util.List;

/**
 * JarPlugin packages artifacts of type "jar". It supports multiple artifacts
 */
public class DepsetPlugin extends LifeCycleImpl implements MetadataAware {
    private Metadata metadata;

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

    public void packageIt() {
        List jars = metadata.getArtifactIds("depset");
        for (Iterator i = jars.iterator(); i.hasNext();) {
            RepoArtifactId id = (RepoArtifactId) i.next();
            String prefix = jars.size() > 1 ? id.getName() : "";
            doPackage(id, prefix);
        }
    }

    private void doPackage(RepoArtifactId id, String prefix) {
        mkdir(getLifeCycle().getPackageOutput());

        Setter setter = new Setter(prefix == null ? getProperties() : getProperties().sub(prefix, false));
        Jar jar = (Jar) getProject().createTask("jar");
        jar.setDestFile(getPackageFile(id));
        FileSet set = getProperties().getFileSet("source");
        jar.addFileset(set);
        // TODO: add remaining attributes
        setter.set(jar, new String[]{"compress", "keepcompression", "encoding", "filesonly", "update"});
        jar.perform();
    }

    private File getPackageFile(RepoArtifactId id) {
        return new File(getLifeCycle().getPackageOutput(), id.toShortString() + "." + metadata.getType(id.getType()).getExtension());
    }
}
